<template>
  <div class="attrs-pannel">
    <a-row :gutter="[0, 10]">
      <template v-for="(item, i) in attrComps" :key="i">
        <AttrComp :label="item.label">
          <template #right>
            <component
              :is="getComponent(item.type as any)"
              size="small"
              v-model:value="attributies[item.name]"
              @change="unionChange(item)"
              :placeholder="item?.placeholder">
              <template v-if="item.type === 'label'">{{ attributies[item.name] }}</template>
            </component>
          </template>
        </AttrComp>
      </template>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue"
import AttrComp from "./component/attr-comp.vue"
import { isBoolean, isNumber } from "lodash"

const props = defineProps<{
  attrs: any
}>()

const emit = defineEmits(["attrChange"])

const components = {
  number: "mars-input-number",
  radio: "mars-switch",
  slider: "mars-slider",
  color: "mars-color-picker",
  combobox: "mars-select",
  textarea: "mars-textarea",
  label: "span",
  text: "mars-input"
}
function getComponent(type: keyof typeof components) {
  return components[type]
}

const attributies = ref<any>(null) // 全部的属性

const attrComps = ref<any[]>([]) // 展示的属性

watch(
  props,
  () => {
    attributies.value = props.attrs ?? {}
    const attrKeys = props.attrs && Object.keys(props.attrs).filter((key) => key !== "my_remark" && key !== "my_name")
    if (attrKeys?.length > 0) {
      attrComps.value = attrKeys.map((k) => {
        let type = "text"
        let label = k
        if (isBoolean(attributies[k])) {
          type = "radio"
        } else if (isNumber(attributies[k])) {
          type = "number"
        }
        if (k === "my_name") {
          label = "业务名称"
        } else if (k === "my_remark") {
          label = "业务备注"
          type = "textarea"
        }
        return { name: k, label, type }
      })
    } else {
      // 演示的内置属性
      attrComps.value = [
        { name: "my_name", label: "业务名称", type: "text", defval: "", placeholder: "请输入名称" },
        { name: "my_remark", label: "业务备注", type: "textarea", defval: "", placeholder: "请输入备注" }
      ]
    }
  },
  {
    immediate: true,
    deep: true
  }
)

function unionChange(item: any) {
  emit("attrChange", {
    name: item.name,
    value: attributies.value[item.name]
  })
}
</script>

<style lang="less" scoped>
.attrs-pannel {
  padding: 14px;
  color: #ffffff;

  .mars-textarea {
    height: 60px;
  }

  .attr_not {
    margin-top: 25px;
    height: 100%;
    line-height: 40px;
    display: flex;
    flex-wrap: nowrap;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    align-items: center;
    color: #9aa5ae;

    .mars-ordernum {
      display: inline-block;
      width: 8px;
      height: 8px;
      background: #173147;
      border: 2px solid #0dd1f5;
      border-radius: 50%;
      margin-right: 7px;
    }
  }
}
</style>
